package cn.geminis.resources.service.controller;

import cn.geminis.resources.service.model.Role;
import cn.geminis.resources.service.model.filter.FunctionFilter;
import cn.geminis.resources.service.model.filter.RoleFilter;
import cn.geminis.resources.service.model.repository.FunctionRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashSet;
import java.util.List;

/**
 * @author Allen
 */
public class RoleController {

    private final FunctionRepository functionRepository;

    public void auth(@PathVariable("id") String id,
                     @RequestBody String[] functionIds) {
        var functions = this.functionRepository.findAll(
                FunctionFilter.builder()
                        .idIn(functionIds)
                        .build()
        );
        var role = this.repository.findById(id).get();
        role.setFunctions(new HashSet<>(functions));
        this.repository.save(role);
    }

    @PutMapping("/{id}/manageRole")
    public void saveManage(@PathVariable("id") String id,
                           @RequestBody List<String> roleIds) {
        var roles = this.repository.findAllById(roleIds);
        var role = repository.findById(id).get();
        role.setRolesManage(new HashSet<>(roles));
        repository.save(role);
    }

    @GetMapping("/{id}/manageRole")
    public List<Role> getManage(@PathVariable("id") String id) {
        return List.copyOf(
                this.repository.findOne(
                                RoleFilter.builder()
                                        .include(new String[]{"rolesManage"})
                                        .id(id)
                                        .build()
                        )
                        .get()
                        .getRolesManage());
    }
}
